package org.ikastola

import ikastola.Constants;

class Student {
	
	String name
	String lastname
	String doctype
	String docnumber
	Date birthdate
	String nationality
	String birthplace
	String status
	String address
	String city
	String zipcode
	String email
	Course course
	Date admdate
	String active
	Service service
	Integer deleted
	Date classCreated
	Date classUpdated
	
	List fees
	List disc
	String phonenumber //telefono preferido (de los tutores)
	
	static transients = ["fees", "disc", "phonenumber"]
	
	static hasMany = [guardians: Guardian, relatives: Student]
	
	static constraints = {
		name blank:false
		lastname blank:false
		docnumber blank: false
		doctype inList: ['1', '2', '3'] //1: DNI, 2: PASAPORTE, 3: OTRO
		birthdate blank: false
		birthplace nullable: true
		status inList: ['1', '2', '3'] //1: Ingresante, 2: Promovido, 3: Repitente
		address blank: false
		nationality blank: false
		address blank: false
		email nullable: true
		course blank: false
		active inList: ['1', '2'] //1:Activo 2:Inactivo
		service nullable: true, unique: true //ver si nullable tiene que ser true o no
		deleted inList: [0, 1]
		classCreated nullable: true
		classUpdated nullable: true
		phonenumber nullable: true
	}
	
	def getFees() {
		if(service != null) {
			return service.fees
		} else {
			return []
		}
	}
	
	def getDisc() {
		if(service != null) {
			return service.discounts
		} else {
			return []
		}
	}
	
	def getPhonenumber() {
		String phones = ""
		for (Guardian g in guardians) {
			phones = phones.isEmpty() ? g.getPreferedPhone() : phones + "/" + g.getPreferedPhone()
		}
		return phones
	}
	
	def getFullName() {
		return name + " " + lastname
	}
	
	def getDoctypeDesc() {
		if ("1".equals(doctype)) {
			return "DNI"
		}
		else if("2".equals(doctype)) {
			return "Pasaporte"
		} else {
			return "Otro"
		}
	}
	
	def static list() {
		return findAllByDeleted(Constants.NOT_DELETED)
	}
	
	def static findAllByGuardians(Guardian g) {
		def c = Student.createCriteria()
		def result = c.get {
			guardians {
				idEq(g.id)
			}
			eq("deleted",Constants.NOT_DELETED)
		}
		return result;
	}
	
	def static findAllByRelatives(Student s) {
		def c = Student.createCriteria()
		def result = c.get {
			relatives {
				idEq(s.id)
			}
			eq("deleted",Constants.NOT_DELETED)
		}
		return result;
	}
	
	def isRelative(Long id) {
		def is = false;
		for (Student s in relatives) {
			if (s.id.equals(id)) {
				is = true
				break
			}
		}
		return is
	}
	
}
